package com.quanyan.place.service.impl;


import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.ServletUtils;
import com.quanyan.orderpay.request.ReqPayInfo;
import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.client.BizPlaceClient;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.apireq.ReqAppUserSearchVo;
import com.quanyan.place.entity.apireq.ReqPlaceOrderDetailVo;
import com.quanyan.place.entity.apireq.ReqPlaceOrderVo;
import com.quanyan.place.entity.apiresp.*;
import com.quanyan.place.entity.vo.RespPlaceTicketInfoVo;
import com.quanyan.place.mapper.*;
import com.quanyan.place.service.ApiPlaceService;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by zhaohui on 2016/5/31.
 * 商家端场馆Service
 */
@Service("apiBizPlaceService")
public class ApiBizPlaceServiceImpl implements BizPlaceClient {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    TbBizPlaceAuthUserMapper tbBizPlaceAuthUserMapper;

    @Autowired
    TbBizPlaceOrderMapper tbBizPlaceOrderMapper;

    @Autowired
    TbBizPlaceOrderItemMapper tbBizPlaceOrderItemMapper;

    @Autowired
    TbBizPlaceMapper tbBizPlaceMapper;

    @Autowired
    TbBizPlaceUnitSalePlanMapper tbBizPlaceUnitSalePlanMapper;

    @Autowired
    ApiPlaceService apiPlaceService;

    @Autowired
    TbBizPlaceRuleMapper tbBizPlaceRuleMapper;

    @Autowired
    UserServiceFacade userServiceFacade;

    @Autowired
    TbBizPlacePayItemMapper tbBizPlacePayItemMapper;

    @Autowired
    TbBizPlaceOrderManagerMapper tbBizPlaceOrderManagerMapper;

    @Autowired
    IBaseService baseService;

    @Autowired
    TbCityMapper tbCityMapper;
    @Autowired
    TbDistrictMapper tbDistrictMapper;

    @Autowired
    TbPlaceTicketSalePlanMapper tbPlaceTicketSalePlanMapper;

    @Autowired
    FinanceCommonManagerMapper financeCommonManagerMapper;

    @Autowired
    TbBizPlaceMemberCardMapper tbBizPlaceMemberCardMapper;
    /**
     * 根据用户Id查找所属的场馆
     *
     * @param reqAppUserSearchVo
     * @return
     */
    @Override
    public PageObj<List<RespBizPlaceBaseInfo>> choosePlace(ReqAppUserSearchVo reqAppUserSearchVo) {
        TbBizPlaceAuthUserExample tbBizPlaceUser = new TbBizPlaceAuthUserExample();
        TbBizPlaceAuthUserExample.Criteria tbBizPlaceUserCriteria = tbBizPlaceUser.createCriteria();

        Integer uid = reqAppUserSearchVo.getUid();
        if (uid != null) {
            tbBizPlaceUserCriteria.andUserIdEqualTo(uid);
        }

        Integer pageNum = reqAppUserSearchVo.getPageNum();
        if (pageNum == null) {
            pageNum = 0;
        }

        Integer pageSize = reqAppUserSearchVo.getPageSize();
        if (pageSize == null) {
            pageSize = Constants.DEFAULT_PAGE_SIZE;
        }
        int total = tbBizPlaceAuthUserMapper.countByExample(tbBizPlaceUser);
        tbBizPlaceUser.setPage(new Page(pageNum * pageSize, pageSize, total));
        List<TbBizPlaceAuthUser> listTbBizPlaceUser = tbBizPlaceAuthUserMapper.selectByExample(tbBizPlaceUser);
        List<RespBizPlaceBaseInfo> listRespBizPlaceBaseInfo = new ArrayList<>();
        if (listTbBizPlaceUser.size() > 0) {
            for (TbBizPlaceAuthUser userList : listTbBizPlaceUser) {
                Integer placeId = userList.getPlaceId();
                APIResponse response = apiPlaceService.placeBaseInfo(placeId);
                RespBizPlaceBaseInfo respBizPlaceBaseInfo = (RespBizPlaceBaseInfo) response.getData();
                listRespBizPlaceBaseInfo.add(respBizPlaceBaseInfo);
            }
        }
        PageObj<List<RespBizPlaceBaseInfo>> result = PageObj.create(total, pageNum, pageSize, listRespBizPlaceBaseInfo);
        return result;
    }

    /**
     * 场馆订单列表
     * @param reqPlaceOrderVo
     * @return
     */
    @Override
    public PageObj<List<RespBizPlaceOrderInfo>> placeOrder(ReqPlaceOrderVo reqPlaceOrderVo) {
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderExampleCriteria = tbBizPlaceOrderExample.createCriteria();
        Integer pageNum = reqPlaceOrderVo.getPageNum();
        if (pageNum == null) {
            pageNum = 0;
        }
        Integer pageSize = reqPlaceOrderVo.getPageSize();
        if (pageSize == null) {
            pageSize = Constants.DEFAULT_PAGE_SIZE;
        }

        Integer placeId = reqPlaceOrderVo.getPlaceId();
        tbBizPlaceOrderExampleCriteria.andPlaceIdEqualTo(placeId);

        //订单状态 1：有效订单 2：历史订单
        Integer status = reqPlaceOrderVo.getStatus();
        if (status == 1) {
            tbBizPlaceOrderExampleCriteria.andDateGreaterThanOrEqualTo(DateUtils.transferLongToDate(System.currentTimeMillis()));
        } else {
            tbBizPlaceOrderExampleCriteria.andDateLessThan(DateUtils.transferLongToDate(System.currentTimeMillis()));
        }
        int total = tbBizPlaceOrderMapper.countByExample(tbBizPlaceOrderExample);
        tbBizPlaceOrderExample.setPage(new Page(pageNum * pageSize, pageSize, total));

        Integer count = getProductUnitInfoByTime(status);
        List<RespBizPlaceOrderInfo> rpoiList = new ArrayList<>();
        if (count > 0) {
            try {
                List<TbBizPlaceOrder> selectByExample = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
                //根据场馆id查找场馆详细
                TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(placeId);
                for (TbBizPlaceOrder placeOrder : selectByExample) {
                    RespBizPlaceOrderInfo rpoi = new RespBizPlaceOrderInfo();
                    rpoi.setOrderNo(placeOrder.getPlaceOrderId());
                    rpoi.setOrderTime(placeOrder.getOrderTime().getTime());
                    String orderDate = DateUtils.transferDateToString(placeOrder.getDate());
                    rpoi.setDate(orderDate);
                    rpoi.setWeek(DateUtils.dayForWeek(orderDate));
                    rpoi.setOrderAmount(placeOrder.getDebit());
                    rpoi.setOrderStatus(placeOrder.getOrderStatus());//订单状态
                    rpoi.setPayStatus(placeOrder.getPayStatus());//支付状态
                    rpoi.setPlaceName(tbBizPlace.getName());
                    rpoi.setPlaceId(placeId);

                    //封装用户信息
                    RespPlaceUserInfo respPlaceUserInfo = getPlaceUserInfo(placeOrder);
                    rpoi.setUserInfo(respPlaceUserInfo);

                    //封装订单列表
                    String placeOrderId = placeOrder.getPlaceOrderId();  //订单编号
                    List<TbBizPlaceOrderItem> tbBizPlaceOrderItem = getTbBizPlaceOrderItem(placeOrderId);

                    List<RespProductUnitInfo> rpuiList = new ArrayList<>();
                    List<RespPlaceTicketInfoVo> ticketInfoVos = new ArrayList<>();
                    for (TbBizPlaceOrderItem orderItem : tbBizPlaceOrderItem){
                        String salePlaceId = orderItem.getSaleId();
                        Byte userType = placeOrder.getUseType();
                        //0：开单 1：包场 2：门票 3：app开单 4：商品
                        if (userType.equals(2)){
                           TbPlaceTicketSalePlan tbPlaceTicketSalePlan = getPlaceTicketSalePlan(orderItem.getUnitSalePlanId());
                            RespPlaceTicketInfoVo ticketInfoVo = new RespPlaceTicketInfoVo();
                            ticketInfoVo.setStartDate(DateTimeUtils.timeToStr(tbPlaceTicketSalePlan.getStartTime()));
                            ticketInfoVo.setEndDate(DateTimeUtils.timeToStr(tbPlaceTicketSalePlan.getEndTime()));
                            ticketInfoVo.setPrice(orderItem.getSalePrice());
                            ticketInfoVo.setTicketName(tbPlaceTicketSalePlan.getTicketName());
                            ticketInfoVo.setTicketCount(orderItem.getTicketCount());
                            ticketInfoVo.setCategoryId(tbPlaceTicketSalePlan.getCategoryId());
                            rpoi.setDate(DateUtils.transferDateToString(orderItem.getConsumeTime()));
                            rpoi.setWeek(DateUtils.transferDateToString(orderItem.getConsumeTime()));
                            ticketInfoVo.setCategoryId(tbPlaceTicketSalePlan.getCategoryId());
                            ticketInfoVo.setCategoryName(baseService.getCommonDataCache("cagetory" + tbPlaceTicketSalePlan.getCategoryId().toString()));
                            ticketInfoVos.add(ticketInfoVo);
                        }else if (userType.equals(0) || userType.equals(1)){
                            //销售计划详情
                            RespProductUnitInfo respProductUnitInfo = getProductUnitInfo(salePlaceId);
                            respProductUnitInfo.setPrice(orderItem.getSalePrice());
                            rpuiList.add(respProductUnitInfo);
                        }

                    }
                    rpoi.setProductUnits(rpuiList);
                    rpoiList.add(rpoi);
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        }
        PageObj<List<RespBizPlaceOrderInfo>> result = PageObj.create(total, pageNum, pageSize, rpoiList);
        return result;
    }

    /**
     * 订单详情
     * @param placeOrderId
     * @return
     */
    private List<TbBizPlaceOrderItem> getTbBizPlaceOrderItem(String placeOrderId) {
        TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
        TbBizPlaceOrderItemExample.Criteria tbBizPlaceOrderItemExampleCriteria = tbBizPlaceOrderItemExample.createCriteria();
        tbBizPlaceOrderItemExampleCriteria.andPlaceOrderIdEqualTo(placeOrderId);
        return tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
    }

    /**
     * 根据销售计划id查询订单详情
     * @param saleId tb_biz_place_unit_sale_plan
     * @return
     */
    private RespProductUnitInfo getProductUnitInfo(String saleId) {
        TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria criteria = tbBizPlaceUnitSalePlanExample.createCriteria();
        criteria.andSaleIdEqualTo(saleId);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = tbBizPlaceUnitSalePlanMapper.selectByExample(tbBizPlaceUnitSalePlanExample);
        if (!CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanList)){
            TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = tbBizPlaceUnitSalePlanList.get(0);
            RespProductUnitInfo respProductUnitInfo = new RespProductUnitInfo();
            respProductUnitInfo.setStartTime(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime()));
            respProductUnitInfo.setEndTime(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime()));
            respProductUnitInfo.setPlaceUnitName(tbBizPlaceUnitSalePlan.getPlaceUnitName());
            respProductUnitInfo.setDate(tbBizPlaceUnitSalePlan.getDate());
            respProductUnitInfo.setCategoryName(baseService.getCommonDataCache("cagetory" + tbBizPlaceUnitSalePlan.getCategoryId().toString()));
            respProductUnitInfo.setCategoryId(tbBizPlaceUnitSalePlan.getCategoryId());
            respProductUnitInfo.setSaleId(tbBizPlaceUnitSalePlan.getId() + "");
            respProductUnitInfo.setDetailsTime(tbBizPlaceUnitSalePlan.getDate());//销售计划时间
            respProductUnitInfo.setCreateTime(tbBizPlaceUnitSalePlan.getCreateTime());
            respProductUnitInfo.setSaleId(tbBizPlaceUnitSalePlan.getSaleId());
            respProductUnitInfo.setMemberPrice(tbBizPlaceUnitSalePlan.getMemberPrice());
            respProductUnitInfo.setPrice(tbBizPlaceUnitSalePlan.getPrice());
            return respProductUnitInfo;

        }
        return null;
    }


    /**
     * 封装用户信息
     * @param tbBizPlaceOrder
     * @return
     */
    private RespPlaceUserInfo  getPlaceUserInfo(TbBizPlaceOrder tbBizPlaceOrder){
        RespPlaceUserInfo respPlaceUserInfo = new RespPlaceUserInfo();
        //respPlaceUserInfo.setUid(tbBizPlaceOrder.getUid());// TODO 场馆订单列表用户待封装
        respPlaceUserInfo.setNickName(tbBizPlaceOrder.getCustomerName());
        respPlaceUserInfo.setMobile(tbBizPlaceOrder.getMobile());
        respPlaceUserInfo.setIsMaster(0);
        respPlaceUserInfo.setLevel(0);
        respPlaceUserInfo.setIcon("");
        APIResponse<RespUserInfoBase> result = null;
        try {
            result = userServiceFacade.queryUserInfo(tbBizPlaceOrder.getUid());
            RespUserInfoBase respUserInfoBase = result.getData();
            if (null != respUserInfoBase){
                respPlaceUserInfo.setNickName(respUserInfoBase.getNickName());
                respPlaceUserInfo.setMobile(respUserInfoBase.getMobile());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  respPlaceUserInfo;
    }
    /**
     * 区分有效订单和历史订单
     * @param status
     * @return
     */
    private Integer getProductUnitInfoByTime(Integer status) {
        TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria tbBizPlaceUnitSalePlanExampleCriteria = tbBizPlaceUnitSalePlanExample.createCriteria();
        if (status == 1) {
            tbBizPlaceUnitSalePlanExampleCriteria.andStartTimeGreaterThanOrEqualTo(DateTimeUtils.strToDate());
        } else {
            tbBizPlaceUnitSalePlanExampleCriteria.andEndTimeLessThan(DateTimeUtils.strToDate());
        }
        return tbBizPlaceUnitSalePlanMapper.countByExample(tbBizPlaceUnitSalePlanExample);
    }

    /**
     * 订单详情
     * @param reqPlaceOrderDetailVo
     * @return
     */
    @Override
    public APIResponse<RespBizPlaceOrderInfo> placeOrderDetail(ReqPlaceOrderDetailVo reqPlaceOrderDetailVo) {
        String token = reqPlaceOrderDetailVo.getToken();
        Integer uid = null;
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        uid = (Integer)httpServletRequest.getAttribute("uid");

        String orderNo = reqPlaceOrderDetailVo.getOrderNo();
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderExampleCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderExampleCriteria.andPlaceOrderIdEqualTo(orderNo);
        tbBizPlaceOrderExampleCriteria.andIsEffectiveEqualTo((byte)1);//TODO 是否有效
        List<TbBizPlaceOrder> selectByExample = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        //响应对象
        RespBizPlaceOrderInfo rbpoi = new RespBizPlaceOrderInfo();
        if (!selectByExample.isEmpty()) {
            //场馆订单
            TbBizPlaceOrder tbBizPlaceOrder = selectByExample.get(0);
            Integer placeId = tbBizPlaceOrder.getPlaceId();
            //场馆对象
            TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(placeId);
            rbpoi.setOrderNo(tbBizPlaceOrder.getPlaceOrderId());
            rbpoi.setOrderTime(tbBizPlaceOrder.getOrderTime().getTime());

            if (baseService.hasComment(tbBizPlaceOrder.getUid(), tbBizPlaceOrder.getPlaceId(), tbBizPlaceOrder.getPlaceOrderId())) {
                rbpoi.setCommented(Constants.IS_YES);
            } else {
                rbpoi.setCommented(Constants.IS_NO);
            }

            Byte useType = tbBizPlaceOrder.getUseType();
            /**订单金额**/
            Map<String,Object> map = new HashMap<>();
            map.put("useType",useType);
            map.put("placeOrderId",tbBizPlaceOrder.getPlaceOrderId());

            BigDecimal debit = tbBizPlaceOrderManagerMapper.clientOrderTotalsPrices(map);

            //rbpoi.setOrderAmount(tbBizPlaceOrder.getDebit());
            rbpoi.setOrderAmount(null != debit ? debit:new BigDecimal(0));
            BigDecimal discountAmount = getDiscountAmount(tbBizPlaceOrder.getPlaceOrderId());
            if (discountAmount != null){
                rbpoi.setPayAmount(discountAmount);
            }else{
                rbpoi.setPayAmount(new BigDecimal(0));
            }

            rbpoi.setPlaceName(tbBizPlace.getName());
            rbpoi.setBizPlaceUrl(tbBizPlace.getBizPlaceUrl());
            rbpoi.setOrderStatus(tbBizPlaceOrder.getOrderStatus());//订单状态
            rbpoi.setPayStatus(tbBizPlaceOrder.getPayStatus());//支付状态
            rbpoi.setPlaceId(placeId);
            rbpoi.setCurrentTime(System.currentTimeMillis());
            rbpoi.setSourceType(tbBizPlaceOrder.getSourceType());
            rbpoi.setAddress(tbBizPlace.getAddress());
            rbpoi.setUseType(tbBizPlaceOrder.getUseType());
            rbpoi.setOrderUse(tbBizPlaceOrder.getOrderUse());
            rbpoi.setEnableRefund(tbBizPlaceOrder.getEnableRefund());
            rbpoi.setCategoryId(tbBizPlaceOrder.getCategoryId());
            //获取场馆城市信息
            TbCity tbCity = tbCityMapper.selectByPrimaryKey(tbBizPlace.getCityId());
            //获取场馆区域信息
            TbDistrict tbDistrict = tbDistrictMapper.selectByPrimaryKey(tbBizPlace.getDistrictId());
            try {
                RespCity respCity = new RespCity();
                BeanUtils.copyProperties(tbCity, respCity);
                rbpoi.setCityObj(respCity);
                RespDistrict respDistrict = new RespDistrict();
                BeanUtils.copyProperties(tbDistrict, respDistrict);
                rbpoi.setDistrictObj(respDistrict);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //根据场馆Id查询场馆规则
            TbBizPlaceRuleExample tbBizPlaceRuleExample = new TbBizPlaceRuleExample();
            TbBizPlaceRuleExample.Criteria tbBizPlaceRuleExampleCriteria = tbBizPlaceRuleExample.createCriteria();
            tbBizPlaceRuleExampleCriteria.andPlaceIdEqualTo(placeId);
            List<TbBizPlaceRule> ruleList = tbBizPlaceRuleMapper.selectByExample(tbBizPlaceRuleExample);
            if (ruleList.isEmpty()){
                rbpoi.setUnsubscribeTime(PlaceConstants.PLACE_UNSUBSCRIBE_TIME);//默认允许退款时间
            } else {
                rbpoi.setUnsubscribeTime(ruleList.get(0).getUnsubscribeTime());//设定退款时间规则
            }

            //封装用户信息
            RespPlaceUserInfo respPlaceUserInfo = getPlaceUserInfo(tbBizPlaceOrder);
            rbpoi.setUserInfo(respPlaceUserInfo);
            rbpoi.setStartDate(getStartDate(uid, reqPlaceOrderDetailVo.getOrderNo(),rbpoi.getUnsubscribeTime()));

            String placeOrderId = tbBizPlaceOrder.getPlaceOrderId();

            //订单支付方式
            rbpoi.setPayInfos(getPayInfos(tbBizPlaceOrder.getPlaceOrderId()));
            //订单详情
            List<TbBizPlaceOrderItem> tbBizPlaceOrderItem = getTbBizPlaceOrderItem(placeOrderId);
            if (!tbBizPlaceOrderItem.isEmpty()) {
                List<RespProductUnitInfo> unitLists = new ArrayList<>();
                List<RespPlaceTicketInfoVo> ticketInfoVos = new ArrayList<>();
                for (TbBizPlaceOrderItem orderItem : tbBizPlaceOrderItem){
                    Byte userType = tbBizPlaceOrder.getUseType();
                    if (userType != null){
                        rbpoi.setUseType(userType);
                        //0：开单 1：包场 2：门票 3：app开单 4：商品
                        if (userType.equals((byte)2)){
                            TbPlaceTicketSalePlan tbPlaceTicketSalePlan = getPlaceTicketSalePlan(orderItem.getUnitSalePlanId());//通过主键查询
                            RespPlaceTicketInfoVo ticketInfoVo = new RespPlaceTicketInfoVo();
                            ticketInfoVo.setStartDate(DateTimeUtils.timeToStr(tbPlaceTicketSalePlan.getStartTime()));
                            ticketInfoVo.setEndDate(DateTimeUtils.timeToStr(tbPlaceTicketSalePlan.getEndTime()));
                            /*List<ReqPayInfo> reqPayInfos = getPayInfos(tbBizPlaceOrder.getPlaceOrderId());
                            for (ReqPayInfo reqPayInfo : reqPayInfos) {
                                if(reqPayInfo.getPayId().equals(10)){
                                    ticketInfoVo.setPrice(tbPlaceTicketSalePlan.getPrice());
                                }else{
                                    ticketInfoVo.setPrice(tbPlaceTicketSalePlan.getPrice());
                                }
                            }*/
                            if (null != orderItem.getOriginPrice()){
                                ticketInfoVo.setPrice(orderItem.getOriginPrice());
                            }else{
                                ticketInfoVo.setPrice(orderItem.getSalePrice());
                            }

                            ticketInfoVo.setTicketName(tbPlaceTicketSalePlan.getTicketName());
                            ticketInfoVo.setTicketCount(orderItem.getTicketCount());
                            ticketInfoVo.setCategoryId(tbPlaceTicketSalePlan.getCategoryId());
                            if(null != orderItem.getMemberPrice()){
                                ticketInfoVo.setMemberPrice(orderItem.getMemberPrice());
                            }else{
                                ticketInfoVo.setMemberPrice(tbPlaceTicketSalePlan.getMemberPrice());
                            }

                            ticketInfoVo.setCategoryName(baseService.getCommonDataCache("cagetory" + tbPlaceTicketSalePlan.getCategoryId().toString()));


                            ticketInfoVos.add(ticketInfoVo);
                            RespProductUnitInfo respProductUnitInfo = new RespProductUnitInfo();
                            respProductUnitInfo.setCategoryId(tbBizPlaceOrder.getCategoryId());
                            respProductUnitInfo.setCategoryName(baseService.getCommonDataCache("cagetory" + tbPlaceTicketSalePlan.getCategoryId().toString()));
                            if (null != orderItem.getOriginPrice()){
                                respProductUnitInfo.setPrice(orderItem.getOriginPrice());
                            }else{
                                respProductUnitInfo.setPrice(orderItem.getSalePrice());
                            }
                            respProductUnitInfo.setStartTime(DateTimeUtils.timeToStr(tbPlaceTicketSalePlan.getStartTime()));
                            respProductUnitInfo.setEndTime(DateTimeUtils.timeToStr(tbPlaceTicketSalePlan.getEndTime()));
                            respProductUnitInfo.setPlaceUnitName(tbPlaceTicketSalePlan.getTicketName());
                            if(null != orderItem.getMemberPrice()){
                                respProductUnitInfo.setMemberPrice(orderItem.getMemberPrice());
                            }else{
                                respProductUnitInfo.setMemberPrice(tbPlaceTicketSalePlan.getMemberPrice());
                            }


                            unitLists.add(respProductUnitInfo);
                        }else if (userType.equals((byte)0) || userType.equals((byte)1) || userType.equals((byte)3)){
                            //销售计划详情
                            RespProductUnitInfo respProductUnitInfo = getProductUnitInfo(orderItem.getSaleId());//通过saleNo查询
                            if (null != orderItem.getOriginPrice()){
                                respProductUnitInfo.setPrice(orderItem.getOriginPrice());
                            }
                            if(null != orderItem.getMemberPrice()){
                                respProductUnitInfo.setMemberPrice(orderItem.getMemberPrice());
                            }else{
                                respProductUnitInfo.setMemberPrice(respProductUnitInfo.getMemberPrice());
                            }
                            if (respProductUnitInfo != null){
                                //respProductUnitInfo.setPrice(orderItem.getSalePrice());
                                unitLists.add(respProductUnitInfo);
                            }
                        }
                    }
                }


                rbpoi.setProductUnits(unitLists);
                rbpoi.setPlaceTicketInfo(ticketInfoVos);
                //销售计划时间
                String setSaleDate = null;
                if (unitLists != null && unitLists.size()>0){
                    Comparator<RespProductUnitInfo> comparator = new Comparator<RespProductUnitInfo>() {
                        @Override
                        public int compare(RespProductUnitInfo o1, RespProductUnitInfo o2) {
                            return o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName()) == 0 ? o1.getStartTime().compareTo(o2.getStartTime()) : o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName());

                        }
                    };
                    Collections.sort(unitLists, comparator);
                    if (null != unitLists.get(0).getDate()){
                        setSaleDate = DateUtils.transferDateToString(unitLists.get(0).getDate());
                        rbpoi.setDate(setSaleDate);
                        rbpoi.setWeek(DateUtils.dayForWeek(setSaleDate));
                    }
                }
                if (ticketInfoVos != null && ticketInfoVos.size() >0){
                    setSaleDate = DateUtils.transferDateToString(tbBizPlaceOrderItem.get(0).getConsumeTime());
                    rbpoi.setDate(setSaleDate);
                    rbpoi.setWeek(DateUtils.dayForWeek(setSaleDate));
                }


            }
            Integer uId = tbBizPlaceOrder.getUid();
            if (null != uId){
                if (uId.equals(uid)){
                    rbpoi.setIsSameUser(Constants.YES);
                }else {
                    rbpoi.setIsSameUser(Constants.NO);
                }
            }
        }else{
            return  APIResponse.returnFail("无数据");
        }
        return APIResponse.returnSuccess(rbpoi);
    }

    private TbPlaceTicketSalePlan getPlaceTicketSalePlan(Integer id){
        return tbPlaceTicketSalePlanMapper.selectByPrimaryKey(id);
    }


    /**
     * 订单实付金额
     * @param placeOrderId
     * @return
     */
    public BigDecimal getDiscountAmount(String placeOrderId){
        Map<String,Object> map = new HashMap();
        List<String> listPlaceOrderId = new ArrayList<>();
        listPlaceOrderId.add(placeOrderId);
        map.put("placeOrderId", listPlaceOrderId);
        return financeCommonManagerMapper.getOrderDiscountAmount(map);
    }

    private Long getStartDate(Integer uid, String orderNo,Integer unsubscribeTime){
        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("orderNo",orderNo);
        queryMap.put("uid", uid);
        List<PlaceOrderSalePlan> placeOrderSalePlanList = tbBizPlaceOrderManagerMapper.selectOrderStatus(queryMap);
        if (!CollectionUtils.isEmpty(placeOrderSalePlanList)){
            String startTime = placeOrderSalePlanList.get(0).getStartTime();
            String startDate = placeOrderSalePlanList.get(0).getDate();
            Date date = DateUtils.dateStrToDate(startDate + " " + startTime);
            if(unsubscribeTime > 0){
                return date.getTime() - unsubscribeTime*60*60*1000;
            }
            return PlaceConstants.NOT_UNSUBSCRIBE_TIMESTAMP;
        }
        return 0L;
    }


    /**
     * 获取订单支付方式
     * @param orderNo
     * @return
     */
    private List<ReqPayInfo> getPayInfos(String orderNo){
       /* TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        TbBizPlacePayItemExample.Criteria criteria = tbBizPlacePayItemExample.createCriteria();
        criteria.andPlaceOrderIdEqualTo(orderNo);
        //criteria.andAmountTypeEqualTo((byte)1);//TODO 收入
        //criteria.andAmountTypeEqualTo((byte)3);//TODO 取消
        List<ReqPayInfo> reqPayInfos = new ArrayList<>();
        List<TbBizPlacePayItem> list = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
        for (TbBizPlacePayItem payItem : list) {
            ReqPayInfo reqPayInfo = new ReqPayInfo();
            reqPayInfo.setPayId(payItem.getPayType());
            reqPayInfo.setAmount(payItem.getAmount());
            if (payItem.getPayType().equals(10)){
                if (null != payItem.getSubjectCode() ){
                    TbBizPlaceMemberCard memberCard = getPlaceMemberInfo(payItem.getSubjectCode());
                    reqPayInfo.setSubjectCode(String.valueOf(memberCard.getCardType()));
                }
            }

            if (payItem.getPayType().equals(11)){

            }

            reqPayInfos.add(reqPayInfo);
        }*/
        Map<String,Object> map = new HashMap<>();
        map.put("placeOrderId",orderNo);
        List<TbBizPlacePayItem> placePayItems = financeCommonManagerMapper.getPayItemGroupByType(map);
        List<ReqPayInfo> respPayLists = new ArrayList<>();
        for (TbBizPlacePayItem placePayItem : placePayItems) {
            ReqPayInfo reqPayInfo = new ReqPayInfo();
            reqPayInfo.setPayId(placePayItem.getPayType());
            reqPayInfo.setAmount(placePayItem.getAmount());
            if (placePayItem.getPayType().equals(10)){
                if (null != placePayItem.getSubjectCode() ){
                    TbBizPlaceMemberCard memberCard = getPlaceMemberInfo(placePayItem.getSubjectCode());
                    reqPayInfo.setSubjectCode(String.valueOf(memberCard.getCardType()));
                }
            }
            respPayLists.add(reqPayInfo);
        }
        return respPayLists;
    }



    public TbBizPlaceMemberCard getPlaceMemberInfo(String cardNo) {
        TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
        TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
        tbBizPlaceMemberCardCriteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);

        // tbBizPlaceMemberCardCriteria.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);//卡状态
        //tbBizPlaceMemberCardCriteria.andCardTypeEqualTo(PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER);//TODO次卡
        //tbBizPlaceMemberCardCriteria.andSourceTypeEqualTo(PlaceConstants.PLACE_MEMBER);//普通会员
        List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
        tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(cardNo);
        if (!StringUtils.isEmpty(cardNo)) {
            tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(cardNo);
        }
        tbBizPlaceMemberCardCriteria.andDeadLineTimeGreaterThan(new Date());//判断截止日期
        return tbBizPlaceMemberCardList.get(0);
    }

    @Override
    public APIResponse<RespBizPlaceOrderInfo> placeOrderDetailClient(ReqPlaceOrderDetailVo reqPlaceOrderDetailVo) {
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer uid = (Integer)httpServletRequest.getAttribute("uid");

        String orderNo = reqPlaceOrderDetailVo.getOrderNo();
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderExampleCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderExampleCriteria.andPlaceOrderIdEqualTo(orderNo);
        tbBizPlaceOrderExampleCriteria.andIsEffectiveEqualTo((byte)1);//TODO 是否有效
        List<TbBizPlaceOrder> selectByExample = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        //响应对象
        RespBizPlaceOrderInfo rbpoi = new RespBizPlaceOrderInfo();
        if (!selectByExample.isEmpty()) {
            //场馆订单
            TbBizPlaceOrder tbBizPlaceOrder = selectByExample.get(0);
            Integer placeId = tbBizPlaceOrder.getPlaceId();
            //场馆对象
            TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(placeId);
            rbpoi.setOrderNo(tbBizPlaceOrder.getPlaceOrderId());
            rbpoi.setOrderTime(tbBizPlaceOrder.getOrderTime().getTime());

            if (baseService.hasComment(tbBizPlaceOrder.getUid(), tbBizPlaceOrder.getPlaceId(), tbBizPlaceOrder.getPlaceOrderId())) {
                rbpoi.setCommented(Constants.IS_YES);
            } else {
                rbpoi.setCommented(Constants.IS_NO);
            }

            Byte useType = tbBizPlaceOrder.getUseType();
            /**订单金额**/
            Map<String,Object> map = new HashMap<>();
            map.put("useType",useType);
            map.put("placeOrderId",tbBizPlaceOrder.getPlaceOrderId());

            //BigDecimal debit = tbBizPlaceOrderManagerMapper.clientOrderTotalsPrices(map);

            //rbpoi.setOrderAmount(tbBizPlaceOrder.getDebit());

            BigDecimal discountAmount = getDiscountAmount(tbBizPlaceOrder.getPlaceOrderId());
            if (discountAmount != null){
                rbpoi.setPayAmount(discountAmount);
            }else{
                rbpoi.setPayAmount(new BigDecimal(0));
            }

            rbpoi.setPlaceName(tbBizPlace.getName());
            rbpoi.setBizPlaceUrl(tbBizPlace.getBizPlaceUrl());
            rbpoi.setOrderStatus(tbBizPlaceOrder.getOrderStatus());//订单状态
            rbpoi.setPayStatus(tbBizPlaceOrder.getPayStatus());//支付状态
            rbpoi.setPlaceId(placeId);
            rbpoi.setCurrentTime(System.currentTimeMillis());
            rbpoi.setSourceType(tbBizPlaceOrder.getSourceType());
            rbpoi.setAddress(tbBizPlace.getAddress());
            rbpoi.setUseType(tbBizPlaceOrder.getUseType());
            rbpoi.setOrderUse(tbBizPlaceOrder.getOrderUse());
            rbpoi.setEnableRefund(tbBizPlaceOrder.getEnableRefund());
            rbpoi.setCategoryId(tbBizPlaceOrder.getCategoryId());
            //获取场馆城市信息
            TbCity tbCity = tbCityMapper.selectByPrimaryKey(tbBizPlace.getCityId());
            //获取场馆区域信息
            TbDistrict tbDistrict = tbDistrictMapper.selectByPrimaryKey(tbBizPlace.getDistrictId());
            try {
                RespCity respCity = new RespCity();
                BeanUtils.copyProperties(tbCity, respCity);
                rbpoi.setCityObj(respCity);
                RespDistrict respDistrict = new RespDistrict();
                BeanUtils.copyProperties(tbDistrict, respDistrict);
                rbpoi.setDistrictObj(respDistrict);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //根据场馆Id查询场馆规则
            TbBizPlaceRuleExample tbBizPlaceRuleExample = new TbBizPlaceRuleExample();
            TbBizPlaceRuleExample.Criteria tbBizPlaceRuleExampleCriteria = tbBizPlaceRuleExample.createCriteria();
            tbBizPlaceRuleExampleCriteria.andPlaceIdEqualTo(placeId);
            List<TbBizPlaceRule> ruleList = tbBizPlaceRuleMapper.selectByExample(tbBizPlaceRuleExample);
            if (ruleList.isEmpty()){
                rbpoi.setUnsubscribeTime(PlaceConstants.PLACE_UNSUBSCRIBE_TIME);//默认允许退款时间
            } else {
                rbpoi.setUnsubscribeTime(ruleList.get(0).getUnsubscribeTime());//设定退款时间规则
            }

            //封装用户信息
            RespPlaceUserInfo respPlaceUserInfo = getPlaceUserInfo(tbBizPlaceOrder);
            rbpoi.setUserInfo(respPlaceUserInfo);
            rbpoi.setStartDate(getStartDate(uid, reqPlaceOrderDetailVo.getOrderNo(),rbpoi.getUnsubscribeTime()));

            String placeOrderId = tbBizPlaceOrder.getPlaceOrderId();
            BigDecimal orderAmount = new BigDecimal(0);
            //订单支付方式
            rbpoi.setPayInfos(getPayInfos(tbBizPlaceOrder.getPlaceOrderId()));

            List<ReqPayInfo> payInfoList = rbpoi.getPayInfos();
            boolean isMember = false;
            for (ReqPayInfo reqPayInfo : payInfoList) {
                if(reqPayInfo.getPayId().equals(10)){
                    isMember = true;
                    break;
                }
            }
            //订单详情
            List<TbBizPlaceOrderItem> tbBizPlaceOrderItem = getTbBizPlaceOrderItem(placeOrderId);
            if (!tbBizPlaceOrderItem.isEmpty()) {
                List<RespProductUnitInfo> unitLists = new ArrayList<>();
                List<RespPlaceTicketInfoVo> ticketInfoVos = new ArrayList<>();
                for (TbBizPlaceOrderItem orderItem : tbBizPlaceOrderItem){
                    Byte userType = tbBizPlaceOrder.getUseType();
                    if (userType != null){
                        rbpoi.setUseType(userType);
                        //0：开单 1：包场 2：门票 3：app开单 4：商品
                        if (userType.equals((byte)2)){
                            TbPlaceTicketSalePlan tbPlaceTicketSalePlan = getPlaceTicketSalePlan(orderItem.getUnitSalePlanId());//通过主键查询
                            RespPlaceTicketInfoVo ticketInfoVo = new RespPlaceTicketInfoVo();
                            ticketInfoVo.setStartDate(DateTimeUtils.timeToStr(tbPlaceTicketSalePlan.getStartTime()));
                            ticketInfoVo.setEndDate(DateTimeUtils.timeToStr(tbPlaceTicketSalePlan.getEndTime()));
                            /*List<ReqPayInfo> reqPayInfos = getPayInfos(tbBizPlaceOrder.getPlaceOrderId());
                            for (ReqPayInfo reqPayInfo : reqPayInfos) {
                                if(reqPayInfo.getPayId().equals(10)){
                                    ticketInfoVo.setPrice(tbPlaceTicketSalePlan.getPrice());
                                }else{
                                    ticketInfoVo.setPrice(tbPlaceTicketSalePlan.getPrice());
                                }
                            }*/
                            if (null != orderItem.getOriginPrice()){
                                ticketInfoVo.setPrice(orderItem.getOriginPrice());
                            }else{
                                ticketInfoVo.setPrice(orderItem.getSalePrice());
                            }

                            ticketInfoVo.setTicketName(tbPlaceTicketSalePlan.getTicketName());
                            ticketInfoVo.setTicketCount(orderItem.getTicketCount());
                            ticketInfoVo.setCategoryId(tbPlaceTicketSalePlan.getCategoryId());
                            if(null != orderItem.getMemberPrice()){
                                ticketInfoVo.setMemberPrice(orderItem.getMemberPrice());
                            }else{
                                ticketInfoVo.setMemberPrice(tbPlaceTicketSalePlan.getMemberPrice());
                            }

                            ticketInfoVo.setCategoryName(baseService.getCommonDataCache("cagetory" + tbPlaceTicketSalePlan.getCategoryId().toString()));


                            ticketInfoVos.add(ticketInfoVo);
                            RespProductUnitInfo respProductUnitInfo = new RespProductUnitInfo();
                            respProductUnitInfo.setCategoryId(tbBizPlaceOrder.getCategoryId());
                            respProductUnitInfo.setCategoryName(baseService.getCommonDataCache("cagetory" + tbPlaceTicketSalePlan.getCategoryId().toString()));
                            if (null != orderItem.getOriginPrice()){
                                respProductUnitInfo.setPrice(orderItem.getOriginPrice());
                            }else{
                                respProductUnitInfo.setPrice(orderItem.getSalePrice());
                            }
                            respProductUnitInfo.setStartTime(DateTimeUtils.timeToStr(tbPlaceTicketSalePlan.getStartTime()));
                            respProductUnitInfo.setEndTime(DateTimeUtils.timeToStr(tbPlaceTicketSalePlan.getEndTime()));
                            respProductUnitInfo.setPlaceUnitName(tbPlaceTicketSalePlan.getTicketName());
                            if(null != orderItem.getMemberPrice()){
                                respProductUnitInfo.setMemberPrice(orderItem.getMemberPrice());
                            }else{
                                respProductUnitInfo.setMemberPrice(tbPlaceTicketSalePlan.getMemberPrice());
                            }

                            unitLists.add(respProductUnitInfo);
                        }else if (userType.equals((byte)0) || userType.equals((byte)1) || userType.equals((byte)3)){
                            //销售计划详情
                            RespProductUnitInfo respProductUnitInfo = getProductUnitInfo(orderItem.getSaleId());//通过saleNo查询
                            if (null != orderItem.getOriginPrice()){
                                respProductUnitInfo.setPrice(orderItem.getOriginPrice());
                            }
                            if(null != orderItem.getMemberPrice()){
                                respProductUnitInfo.setMemberPrice(orderItem.getMemberPrice());
                            }else{
                                respProductUnitInfo.setMemberPrice(respProductUnitInfo.getMemberPrice());
                            }
                            if (respProductUnitInfo != null){
                                //respProductUnitInfo.setPrice(orderItem.getSalePrice());
                                unitLists.add(respProductUnitInfo);
                            }
                        }
                    }

                    if (isMember){
                        orderAmount = orderAmount.add(orderItem.getMemberPrice());
                    }else {
                        orderAmount = orderAmount.add(orderItem.getOriginPrice());
                    }

                }
                rbpoi.setOrderAmount(orderAmount);
                rbpoi.setProductUnits(unitLists);
                rbpoi.setPlaceTicketInfo(ticketInfoVos);
                //销售计划时间
                String setSaleDate = null;
                if (unitLists != null && unitLists.size()>0){
                    Comparator<RespProductUnitInfo> comparator = new Comparator<RespProductUnitInfo>() {
                        @Override
                        public int compare(RespProductUnitInfo o1, RespProductUnitInfo o2) {
                            return o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName()) == 0 ? o1.getStartTime().compareTo(o2.getStartTime()) : o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName());

                        }
                    };
                    Collections.sort(unitLists, comparator);
                    if (null != unitLists.get(0).getDate()){
                        setSaleDate = DateUtils.transferDateToString(unitLists.get(0).getDate());
                        rbpoi.setDate(setSaleDate);
                        rbpoi.setWeek(DateUtils.dayForWeek(setSaleDate));
                    }
                }
                if (ticketInfoVos != null && ticketInfoVos.size() >0){
                    setSaleDate = DateUtils.transferDateToString(tbBizPlaceOrderItem.get(0).getConsumeTime());
                    rbpoi.setDate(setSaleDate);
                    rbpoi.setWeek(DateUtils.dayForWeek(setSaleDate));
                }


            }
            Integer uId = tbBizPlaceOrder.getUid();
            if (null != uId){
                if (uId.equals(uid)){
                    rbpoi.setIsSameUser(Constants.YES);
                }else {
                    rbpoi.setIsSameUser(Constants.NO);
                }
            }
        }else{
            return  APIResponse.returnFail("无数据");
        }
        return APIResponse.returnSuccess(rbpoi);
    }
}
